package com.mingqi.enetconnected.service;

import android.content.Intent;
import android.media.MediaPlayer;

import com.mingqi.enetconnected.R;
import com.mingqi.enetconnected.base.MyApplication;
import com.mingqi.enetconnected.daemon.AbsHeartBeatService;
import com.mingqi.enetconnected.notice.NotifyTools;
import com.mingqi.enetconnected.primary.MainActivity;
import com.mingqi.enetconnected.util.log.Log2FileUtils;
import com.netease.nimlib.sdk.util.NIMUtil;

import org.greenrobot.eventbus.EventBus;

public class BackgroundService extends AbsHeartBeatService {
    public final static String TAG = BackgroundService.class.getSimpleName();
    private MediaPlayer mMediaPlayer;

    @Override
    public void onDestroy() {
        super.onDestroy();
        stopPlayMusic();
    }

    @Override
    public void onStartService() {
        try {

            Intent mainIntent = new Intent(this, MainActivity.class);
            mainIntent.setAction(Intent.ACTION_MAIN);
            mainIntent.addCategory(Intent.CATEGORY_LAUNCHER);

            NotifyTools.showNotificationNormal(this, 0, MyApplication.getSysIcon(),
                    this.getString(R.string.app_name), "", mainIntent);

        } catch (Exception e) {
            e.printStackTrace();
        }
        mMediaPlayer = MediaPlayer.create(getApplicationContext(), R.raw.silent);
        mMediaPlayer.setLooping(true);
        new Thread(new Runnable() {
            @Override
            public void run() {
                startPlayMusic();
            }
        }).start();
    }

    @Override
    public void onStopService() {
        stopPlayMusic();
    }

    @Override
    public long getDelayExecutedMillis() {
        return 5 * 1000;
    }

    @Override
    public long getHeartBeatMillis() {
        return 30 * 1000;
    }

    @Override
    public void onHeartBeat() {
        Log2FileUtils.e("onHeartBeat=="+NIMUtil.isMainProcess(this));
    }

    @Override
    public void onLowMemory() {
        super.onLowMemory();
    }

    private void startPlayMusic() { // 启动后台播放音乐
        if (mMediaPlayer != null) {
            Log2FileUtils.g(TAG + "mMediaPlayer.start()");
            mMediaPlayer.start();
        }
    }

    private void stopPlayMusic() { // 关闭后台播放音乐
        if (mMediaPlayer != null) {
            Log2FileUtils.g(TAG + "mMediaPlayer.stopPlayMusic()");
            mMediaPlayer.stop();
            mMediaPlayer = null;
        }
    }

}
